<template>
  <div>
    <el-table-form
      ref="dataForm"
      :model="shop"
    >
      <el-form-item label="商品分类:" prop="orgSNNo">
        <el-tree-select
          v-model="shop.gTypeId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称:" class="merge-item">
        <el-select v-model="shop.goodsId" filterable clearable>
          <el-option
            v-for="(l, i) in goodsTypesDetailList"
            :key="i"
            :value="l.goodsId"
            :label="l.goodsName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生效机构:" prop="orgSNNo">
        <el-tree-select
          v-model="shop.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData,
          }"
          @node-click="selectOrgTreeChange"
        />
      </el-form-item>
      <el-form-item label="波动方式:" class="merge-item">
        <el-select v-model="shop.priceType" clearable>
          <el-option
            v-for="(l, i) in priceTypeMap"
            :key="i"
            :value="l.value"
            :label="l.desc"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格:">
        <el-input
          v-model.trim="shop.price"
          clearable
          placeholder="请输入"
          @keyup.enter.native="search"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-checkbox v-model="disAbledStatu" style=" margin-right: 10px; margin-left: 10px;">排除已失效</el-checkbox>
        <el-button v-permission="[10020302,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="[10020302,2]"
          type="primary"
          style="margin-right: 5px;"
          icon="el-icon-plus"
          @click="add"
        >新增调价</el-button>
        <el-button
          v-permission="[10020302,3]"
          type="primary"
          icon="el-icon-download"
          :loading="$loadingPlugin.exportFile"
          @click="exportFile"
        >导出</el-button>
      </div>
    </div>
    <div class="page_main">
      <div class="left">
        <div class="info-title">
          <span class="title-icon" />
          <span>商品信息</span>
        </div>
        <lb-table
          ref="lbTable_left"
          v-loading="$loadingPlugin.fetchData"
          v-el-height-adaptive-table="{ bottomOffset: 10 }"
          border
          element-loading-text="加载中"
          :column="tableDataLeft.column"
          :data="tableDataLeft.data"
          highlight-current-row
          :total="tableDataLeft.total"
          custom-column
          height="300"
          @current-change="selectLeftTable"
          @fetch="fetchDataLeft"
        />
      </div>
      <div class="right">
        <div class="info-title">
          <span class="title-icon" />
          <span>客户信息</span>
        </div>
        <lb-table
          ref="tableData_right"
          v-loading="$loadingPlugin.fetchData"
          v-el-height-adaptive-table="{ bottomOffset: 10 }"
          border
          element-loading-text="加载中"
          :column="column"
          :data="tableDataRight.data"
          pagination
          highlight-current-row
          :total="tableDataRight.total"
          @fetch="fetchDataRight"
          @expand-change="expandChange"
        />
      </div>
    </div>
    <addSelectPrice
      ref="addSelectPrice"
      :goods-tree-data="goodsTreeData"
      :org-tree-data="orgTreeData"
      @upDataTable="upDataTable"
    />
    <allAdjust
      ref="allAdjust"
      :goods-tree-data="goodsTreeData"
      :org-tree-data="orgTreeData"
      @afterSave="afterSave"
      @upDataTable="upDataTableAfterSave"
    />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import {
    goodsTypeDetail,
    CmsSpecialPriceOriented,
    CmsSpecialPriInfo,
    specialPriceGoodsExport,
    CmsSpecialconfigUpdateDetail
  } from '@/api'
  import { parseTime } from '@/utils'
  export default {
    name: 'shopOrientedMode',
    components: {
      addSelectPrice: require('./addSelectPrice.vue').default,
      allAdjust: require('./allAdjust.vue').default
    },
    props: ['orgTreeData', 'goodsTreeData', 'exportDomain'],

    data() {
      return {
        detailList: [],
        startNum: 0, // 用作首次加载表格不执行
        goodsTypesDetailList: [],
        disAbledStatu: true,
        priceTypeMap: [
          { value: 1, desc: '下浮', key: 'Fluctuating' },
          { value: 2, desc: '固定', key: 'Fixed' }
        ],
        shop: {
          gTypeId: null,
          goodsId: null
        },
        cols: [
          {
            prop: 'createTime',
            label: '操作时间',
            render: (h, { row }) => (
            <span>
              {row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            prop: 'createUser',
            label: '操作员'
          },
          {
            prop: 'goodsName',
            label: '商品名称'
          },
          {
            prop: 'remark',
            label: '状态',
            render: (h, { row }) => <span>{row.remark && row.remark + '商品'}</span>
          },
          {
            prop: 'priceType',
            label: '波动方式',
            render: (h, { row }) => (
            <span>
              {row.priceType &&
                this.priceTypeMap.find((l) => l.value === row.priceType).desc}
            </span>
          )
          },
          {
            prop: 'price',
            label: '波动价格',
            render: (h, { row, $index, column }) => (
            <span>
              {row[column.property] ? (row[column.property] * 1).toFixed(2) : ''}
            </span>
          )
          },
          {
            prop: 'startDt',
            label: '时效范围',
            render: (h, { row }) => (
            <span>
              {row.startDt &&
                row.endDt &&
                parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') +
                  '~' +
                  parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')}
            </span>
          )
          },
          {
            prop: 'scopeOrgName',
            label: '生效机构'
          }
        ],
        tableDataLeft: {
          data: [],
          column: [
            { label: '商品名称', prop: 'goodsName', width: 200 },
            {
              label: '波动方式',
              prop: 'priceType',
              render: (h, { row }) => (
              <span>
                {row.priceType &&
                  this.priceTypeMap.find((l) => l.value === row.priceType).desc}
              </span>
            )
            },
            {
              label: '波动价格',
              prop: 'price',
              render: (h, { row, column }) => (
              <span>{row.price && row.price.toFixed(2)}</span>
            )
            },
            {
              label: '操作',
              prop: 'op',
              render: (h, { row, column }) => (
              <span
                v-permission={[10020302, 4]}
                onClick={() => {
                  this.allAdjust(row)
                }}
                style='color:blue;cursor: pointer'
              >
                批量调价
              </span>
            )
            }
          ]
        },
        tableDataRight: {
          total: 0,
          data: []
        },
        rightParams: {}
      }
    },
    computed: {
      column: function() {
        return [
          { type: 'index' },
          {
            type: 'expand',
            render: (h, { row }) => {
              return (
                  <div>
                 {this.detailList[row.categoryDetailId] && this.detailList[row.categoryDetailId].map(item => {
                   return <div class='detail-marge'>
                    <span>【{ item.createTime && this.formatDate(item.createTime) }】</span>
                    <span>操作员【{ item.createUser}】</span>
                    <span>{item.remark}商品【{ item.goodsName}】的报价</span>
                    <span>【波动方式：{item.priceType && this.priceTypeMap.find(l => l.value === item.priceType).desc};波动价格：{ item.price ? (item.price * 1).toFixed(2) : '0.00'}元；时效范围：{(item.startDt && item.endDt) && this.formatDate(item.startDt) + '~' + this.formatDate(item.endDt) }生效机构：{item.scopeOrgName} 】</span>
                   </div>
                 })}
                </div>
                // <div>
                //   <lb-table
                //     ref='lbTable'
                //     border
                //     element-loading-text='加载中'
                //     column={this.cols}
                //     data={row.detailList}
                //     pagination={false}
                //   />
                // </div>
                )
            }
          },
          { label: '客户名称', prop: 'csmName', width: 120 },
          {
            label: '状态',
            prop: 'checkStatus',
            width: 80,
            render: (h, { row, column }) => <span>{this.statusMap(row, column)}</span>
          },
          {
            label: '时效范围',
            prop: 'startDt',
            width: 300,
            render: (h, { row, column }) => <span>{this.timeformat(row, column)}</span>
          },
          { label: '客户编号', prop: 'csmCode', width: 80 },
          { label: '客户电话', prop: 'contactPhone', width: 120 },
          { label: '客户地址', prop: 'csmAddress', width: 250 },
          { label: '生效机构', prop: 'scopeOrgName', width: 180 },
          { label: '关键字', prop: 'keyName', width: 80 }
        ]
      }
    },
    created() {
      this.shop.gTypeId = this.goodsTreeData[0].gtId
      this.selectTreeChange({ gtId: this.goodsTreeData[0].gtId })
    },
    methods: {
      async search() {
        // console.log(this.shop)
        // try {
        //   var params = { ...this.shop }
        //   var res = await CmsSpecialPriceOriented(params)
        //   console.log(res)
        // } catch (e) {
        //   console.log(e)
        // }
        this.fetchDataLeft()
      },
      // 更新商品信息
      upDataTable() {
        this.fetchDataUpdate()
      },
      // 更新客户信息
      upDataTableAfterSave() {
        this.$refs.tableData_right.fetch()
      },
      async fetchDataLeft() {
        // 首次不加载
        if (!this.startNum) {
          this.startNum++
          return
        }
        // ////////
        if (JSON.stringify(this.shop) === '{}') {
          return
        }
        if (!this.shop.goodsId) {
          this.$message.warning('请选择商品')
          return
        }
        const params = {
          ...this.shop,
          pageIndex: 1,
          pageSize: 999
        }
        const res = await CmsSpecialPriceOriented(params)
        this.tableDataLeft.data = res.data
      // if (currentPage === 1) this.tableData.total = res.data.total
      },
      async fetchDataUpdate() {
        const params = {
          ...this.shop,
          pageIndex: 1,
          pageSize: 999
        }
        const res = await CmsSpecialPriceOriented(params)
        this.tableDataLeft.data = res.data
      },
      async afterSave() {
        await this.fetchDataLeft()
      },
      async fetchDataRight({ pageIndex = 1, pageSize = 20 }, data) {
        if (JSON.stringify(this.shop) === '{}') {
          return
        }
        const params = {
          ...this.rightParams,
          pageIndex,
          pageSize
        }
        if (!params.price) return
        const res = await CmsSpecialPriInfo(params)
        this.tableDataRight.data = res.data.rows.map(l => {
          return { ...l, detailList: [] }
        })
        if (pageIndex === 1) this.tableDataRight.total = res.data.total
      },
      selectLeftTable(val) {
        console.log(val, 'val')
        const params = {
          goodsId: val.goodsId,
          priceType: val.priceType,
          price: val.price,
          scopeOrgSNNo: this.shop.orgSNNo
        }
        this.rightParams = params
        if (this.disAbledStatu) params['expired'] = 2
        this.fetchDataRight({}, params)
      },

      // 选择商品分类
      async selectTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        // this.shop.goodsId = ''
        if (value.gtId) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 选择生效机构
      selectOrgTreeChange(value) {
      // this.orgSNNo = value.orgSNNo
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
        // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      // 批量调价
      allAdjust(row) {
        console.log('数据', row)
        this.$refs.allAdjust.open(row)
      },
      // 状态文本格式化
      statusMap(row, column) {
        const nowDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        const endDt = parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')
        if (endDt < nowDt) {
          return '已失效'
        }
        const val = row[column.property]
        if (val === 0) {
          return '一级待审'
        } else if (val === 1) {
          return '二级待审'
        } else if (val === 2) {
          return '已生效'
        } else if (val === 4) {
          return '已驳回'
        }
        return ''
      },
      // 新增调价
      add() {
        this.$refs.addSelectPrice.open()
      },
      // 时间格式化
      timeformat(row, column) {
        const startTime = parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}')
        const endTime = parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')
        return `${startTime}至${endTime}`
      },
      // 导出
      async exportFile() {
        this.$confirm('确定要导出吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            var list = JSON.parse(JSON.stringify(this.column))
            const value = {}
            list.forEach((l) => {
              value[l.prop] = l.label
              return value
            })
            if (!this.shop.goodsId || !this.rightParams.goodsId) {
              this.$message.warning('请选择商品')
              return
            }
            const params = {
              kv: value,
              paramData: { ...this.rightParams }
            }
            await specialPriceGoodsExport(params).then((res) => {
              window.open(
                `${this.exportDomain}/page/export/frame?key=${res.data}`,
                '_blank'
              )
            })
          })
          .catch(() => {})
      },
      // 列表行详情
      async expandChange(row) {
        const res = await CmsSpecialconfigUpdateDetail({
          categoryDetailId: row.categoryDetailId,
          csmId: row.csmId,
          pageSize: 10
        })
        // this.$set(row, 'detailList', res.data)
        this.$set(this.detailList, row.categoryDetailId, [])
        this.$set(this.detailList, row.categoryDetailId, res.data)
      // console.log('增加后的数据', this.tableDataLeft.data)
      },
      formatDate(time) {
        const date = new Date(time)
        date.setHours(date.getHours() - 8)
        return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.form_right {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 40%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-bottom: 10px;
  font-size: 14px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 14px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
.page_main {
  display: flex;
  box-sizing: border-box;
  .left {
    width: 30%;
    padding: 5px;
    // border: 1px solid #ebeff6;
  }
  .right {
    width: 70%;
    padding: 5px;
  }
  .info {
    display: inline-block;
    overflow: hidden;
    font-size: 12px;
    color: #999;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
  }
}
/deep/.detail-marge {
  margin-bottom: 8px;
}
</style>
